package com.wft.design.oauth.controller;

import com.wft.design.common.security.annotation.PreAuthorize;
import com.wft.design.common.security.bean.AccessToken;
import com.wft.design.common.security.bean.Authentication;
import com.wft.design.common.security.service.AuthenticationManager;
import com.wft.design.oauth.constant.GrantType;
import com.wft.design.oauth.entity.OauthParameter;
import com.wft.design.oauth.factory.GrantModeStrategyFactory;
import com.wft.design.oauth.service.TokenService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author WFT
 * @date 2019/12/31
 * description: 认证控制器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/auth")
public class AuthenticationController {

    private final GrantModeStrategyFactory grantModeStrategyFactory;
    private final AuthenticationManager authenticationManager;
    private final TokenService tokenService;

    private final static String CLIENT_ID = "1147045090791956482";
    private final static String CLIENT_SECRET = "c1940b54-288d-11ea-b6bb-0242ac120004";

    /**
     * 登录接口
     * @param parameter 参数
     * @return com.wft.design.common.security.bean.AccessToken
     */
    @PostMapping(value = "/login")
    public AccessToken login(@RequestBody OauthParameter parameter){
        parameter.setClientId(CLIENT_ID);
        parameter.setClientSecret(CLIENT_SECRET);
        Authentication authentication = this.grantModeStrategyFactory.getGrantModeService(GrantType.password.toString()).checking(parameter);
        //  生成Token
        return this.tokenService.generateToken(authentication,parameter.getRememberMe());
    }

    /**
     * 退出登录
     * @param request 请求
     */
    @PreAuthorize
    @GetMapping(value = "/logout")
    public void logout(HttpServletRequest request){
        this.authenticationManager.removeAuthentication(request);
    }

}
